//
//  Panel.m
//  NXTRemoteController
//
//  Created by naceka on 14.05.12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "Panel.h"


@implementation Panel


- (id)initWithFrame:(CGRect)frame andRobot:(Robot *) r{
    
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
		
		robot = r;
		
		//background image
		UIColor * background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"panel.png"]];
		self.backgroundColor = background;
		[background release];
		
		//add labels
		for (int i = 0; i < 4; i++) {
			UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(i*192 + 30, 9, 96, 30)];
			label.text = [[NSString alloc] initWithFormat: @"Сенсор #%d", i + 1];
			label.backgroundColor = [UIColor clearColor];
			label.textColor = [UIColor whiteColor];
			[self addSubview:label];
			
			sensorType[i] = [[UILabel alloc] initWithFrame:CGRectMake(i*192 + 30, 57, 96, 30)];
			sensorType[i].backgroundColor = [UIColor clearColor];
			sensorType[i].textColor = [UIColor whiteColor];
			[self addSubview:sensorType[i]];
			
			sensorData[i] = [[UILabel alloc] initWithFrame:CGRectMake(i*192 + 30, 105, 96, 30)];
			sensorData[i].backgroundColor = [UIColor clearColor];
			sensorData[i].textColor = [UIColor whiteColor];
			[self addSubview:sensorData[i]];
		}
		
		//set type and data to "--"
		[self cleanSensorsTypeAndData];
		
		//register in notification center
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceConnected) name:@"RobotDeviceConnected" object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceDisconnected) name:@"RobotDeviceDisconnected" object:nil];		
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code.
}
*/

- (void)dealloc {
    [super dealloc];
}


- (void) setSensor:(int) sensorNumber Type:(NSString *) type {
	sensorType[sensorNumber].text = type;
}
- (void) setSensor:(int) sensorNumber Data:(NSString *) data {
	sensorData[sensorNumber].text = data;
}

- (void) cleanSensorsTypeAndData {
	for (int i = 0; i < 4; i++) {
		sensorType[i].text = @"--";
		sensorData[i].text = @"--";
	}
	
}

- (void) deviceConnected {
	NSLog(@"update sensor types");
	for (int i = 0; i < 4; i++) {
		if ([robot sensorAt:i] != nil ) {
			sensorType[i].text = [[robot sensorAt:i] getTypeString];
		}
	}	
}

- (void) deviceDisconnected {
	//flush data and sensor types
	[self cleanSensorsTypeAndData];	
}

//SensorDataDelegate
- (void) sensorDataUpdated:(int) sn {
	//update data
	sensorData[sn].text = [[robot sensorAt:sn] getData];
}

@end
